﻿using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("图片转base64脚本工具");
            bool status1 = true;
            bool status2 = true;
            ImageFormat format = ImageFormat.Bmp;
            do
            {
                try
                {
                    Console.Write("请输入带后缀文件名：");
                    string fileName = Console.ReadLine();
                    System.Drawing.Image MyImage = System.Drawing.Image.FromFile(fileName);

                    do
                    {
                        Console.WriteLine("请选择图片格式：");
                        Console.WriteLine("1 - JPG/JPEG");
                        Console.WriteLine("2 - PNG");
                        Console.WriteLine("3 - BMP");
                        Console.Write("请输入数字：");
                        if (false == Int32.TryParse(Console.ReadLine(), out int num)) continue;

                        switch (num)
                        {
                            case 1:
                                format = ImageFormat.Jpeg;
                                break;
                            case 2:
                                format = ImageFormat.Png;
                                break;
                            case 3:
                                format = ImageFormat.Bmp;
                                break;
                            default:
                                continue;
                        }
                        status2 = false;
                    } while (status2);

                    using (var ms = new MemoryStream())
                    {
                        // Convert Image to byte[]
                        MyImage.Save(ms, format);
                        byte[] imageBytes = ms.ToArray();

                        // Convert byte[] to Base64 String
                        string base64String = Convert.ToBase64String(imageBytes);
                        File.WriteAllText("Result.txt", "data:image/" + format.ToString().ToLower() + ";base64," + base64String);
                    }
                }
                catch
                {
                    continue;
                }
                status1 = false;
            } while (status1);
            Console.WriteLine("转换成功！");
            Console.Read();
        }
    }
}
